﻿<%@ Control Language="C#" %>
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<%@ Import Namespace="ArbolandiaBL" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
    public delegate void ReloadGridFromUsr();
    public event ReloadGridFromUsr reloadgrid;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!ArbolandiaBL.Security.ValidLogin())
        {
            X.AddScript("this.parent.LogOut();");


        }
        if (!X.IsAjaxRequest)
        {
            dpfImageSizeCat.Text = ConstantsBL.SIZE_IMAGE_PRODUCT_CATEGORY_TITLE;
        }
    }

    protected void ReloadGridParent()
    {
        reloadgrid();
    }

    public Store GridStore { get; set; }

    public void Show()
    {
        this.categoryDetailsWindow.Show();
    }

    public void SetCategory(Product_Category category)
    {
        pnlImagecategory.Reset();
        CategoryInfoTab.SetValues(category);
        ReloadGridImage(category.Id);
    }
    protected void SaveCategory(object sender, DirectEventArgs e)
    {
        int id;
        int.TryParse(e.ExtraParams["id"], out id);

        Product_Category cat = new Product_Category();
        cat.Id = id;
        cat.MetaKeywords = this.MetaKeywords.Text;
        cat.FullDescription = this.FullDescription.Text;

        new Service().InsertUpdateCategory(cat);

        this.categoryDetailsWindow.Hide();
        if (id == 0)
        {
            ReloadGridParent();
        }
        else
        {
            var record = this.GridStore.GetById(id);
            CategoryInfoTab.UpdateRecord(record);
            record.Commit();
        }
    }
    protected void ReloadGridImage(Int32 categoryId)
    {
        storeImagesSubcategory.DataSource = new Service().GetPictureCategory(categoryId);
        storeImagesSubcategory.DataBind();
    }
    protected void UploadClick(object sender, DirectEventArgs e)
    {
        string tpl = "Uploaded file: {0}<br/>Size: {1} bytes";
        if (this.uploadField.HasFile &&
            (this.uploadField.PostedFile.FileName.ToLower().Contains(".png") ||
             this.uploadField.PostedFile.FileName.ToLower().Contains(".jpg") ||
            this.uploadField.PostedFile.FileName.ToLower().Contains(".jpeg"))
            )
        {
            Int32 categoryId; Int32.TryParse(e.ExtraParams["id"], out categoryId);
            Guid pictureGuid = Guid.NewGuid();
            string extension = Path.GetExtension(this.uploadField.PostedFile.FileName);
            string pathfile = System.Configuration.ConfigurationManager.AppSettings["imagesfolder"];
            string filename = pictureGuid + extension;
            pathfile = Server.MapPath(@"~" + @"\" + pathfile + @"\" + filename);

            this.uploadField.PostedFile.SaveAs(pathfile);
            new Service().SaveRezizeImage(pathfile, uploadField.PostedFile.InputStream, ConstantsBL.SIZE_IMAGE_PRODUCT_CATEGORY_HEIGHT, ConstantsBL.SIZE_IMAGE_PRODUCT_CATEGORY_WIDTH);
            //Save Guid
            Picture pic = new Picture()
            {
                IsFullSize = false,
                Url = "http://hostimages/" + System.Configuration.ConfigurationManager.AppSettings["imagesfolder"] + "/" + filename,
                ToolTip = "",
                MimeType = "",
                LinkUrl = "",
                IsEnabled = true,
                GuidId = pictureGuid,
                GroupdId = 0
            };
            new Service().InsertPictureCategory(categoryId, pictureGuid, pic);

            ReloadGridImage(categoryId);
            X.Msg.Show(new MessageBoxConfig
            {
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.INFO,
                Title = "Exito",
                Message = string.Format(tpl, this.uploadField.PostedFile.FileName, this.uploadField.PostedFile.ContentLength)
            });


        }
        else
        {
            X.Msg.Show(new MessageBoxConfig
            {
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.ERROR,
                Title = "Error",
                Message = "No se pudo cargar el archivo"
            });
        }
    }
    protected void btnDeleteImageCategory_Click(object sender, DirectEventArgs e)
    {
        Int32 categoryId; Int32.TryParse(e.ExtraParams["id"], out categoryId);
        new Service().DeletePictureCategory(categoryId);
        ReloadGridImage(categoryId);
        Ext.Net.Notification.Show(new Ext.Net.NotificationConfig
        {
            Title = Constants.TITLE_DELETE,
            Icon = Ext.Net.Icon.PageSave,
            AutoHide = true,
            Html = Constants.NOTIFY_DELETED
        });
    }

</script>
<ext:Window ID="categoryDetailsWindow" runat="server" Icon="Group" Title="Categoria Detalle"
    Width="700" Height="450" AutoShow="false" Modal="true" Hidden="true" Layout="Fit">
    <Items>
        <ext:TabPanel ID="TabPanel1" runat="server" ActiveTabIndex="0" Border="false" DeferredRender="false">
            <Items>
                <ext:FormPanel ID="CategoryInfoTab" runat="server" Title="Informacion" Icon="ChartOrganisation"
                    DefaultAnchor="100%" BodyPadding="5">
                    <Items>
                        <ext:TextField ID="Idcategory" runat="server" FieldLabel="ID" Disabled="true" Name="Id" />
                        <ext:TextField ID="Namecategory" runat="server" FieldLabel="Nombre" Name="Name" Disabled="true" />
                        <ext:TextField ID="FullDescription" Height="50" FieldLabel="Descripcion General"
                            LabelAlign="Top" runat="server" Name="FullDescription">
                        </ext:TextField>
                        <ext:HtmlEditor runat="server" Height="160" ID="MetaKeywords" LabelAlign="Top" Name="MetaKeywords"
                            AutoScroll="true" />
                    </Items>
                </ext:FormPanel>
                <ext:FormPanel ID="pnlImagecategory" runat="server" Title="Imagen Subcategoria" Icon="LayoutContent"
                    DefaultAnchor="100%" BodyPadding="5">
                    <Items>
                        <ext:FieldSet ID="FieldSet1" runat="server">
                            <Items>
                                <ext:FieldContainer ID="fieldcontainer2" runat="server" Layout="HBoxLayout">
                                    <Items>
                                        <ext:FileUploadField ID="uploadField" runat="server" Width="400" Icon="Attach" AllowBlank="false">
                                        </ext:FileUploadField>
                                        <ext:ToolbarSeparator ID="ToolbarSeparator1" runat="server">
                                        </ext:ToolbarSeparator>
                                        <ext:Button ID="btnUploadImage" runat="server" Text="Subir Foto">
                                            <DirectEvents>
                                                <Click OnEvent="UploadClick" Before="if (!#{pnlImagecategory}.getForm().isValid()) { return false; } 
                                                            Ext.Msg.wait('Cargando Imagen...', 'Cargando');" Failure="Ext.Msg.show({ 
                                                            title   : 'Error', 
                                                            msg     : 'Error during uploading', 
                                                            minWidth: 200, 
                                                            modal   : true, 
                                                            icon    : Ext.Msg.ERROR, 
                                                            buttons : Ext.Msg.OK 
                                                        });">
                                                    <ExtraParams>
                                                        <ext:Parameter Name="id" Value="#{Idcategory}.getValue()" Mode="Raw" />
                                                    </ExtraParams>
                                                </Click>
                                            </DirectEvents>
                                        </ext:Button>
                                        <ext:DisplayField ID="dpfImageSizeCat" runat="server" LabelAlign="Right" />
                                    </Items>
                                </ext:FieldContainer>
                                <ext:FieldContainer ID="fieldcontainer3" runat="server">
                                    <Items>
                                        <ext:GridPanel ID="gridImageSubcategory" runat="server" ClientIDMode="Static" AutoScroll="true"
                                            Height="300">
                                            <Store>
                                                <ext:Store ID="storeImagesSubcategory" runat="server">
                                                    <Model>
                                                        <ext:Model ID="Model5" runat="server" IDProperty="GuidId">
                                                            <Fields>
                                                                <ext:ModelField Name="GuidId" />
                                                                <ext:ModelField Name="Name" />
                                                                <ext:ModelField Name="url" />
                                                            </Fields>
                                                        </ext:Model>
                                                    </Model>
                                                </ext:Store>
                                            </Store>
                                            <ColumnModel>
                                                <Columns>
                                                    <ext:TemplateColumn ID="TemplateColumn2" runat="server" Text="Archivo" Flex="15"
                                                        DataIndex="url" TemplateString='<img style="width:60px;height:45px;" src="{url}" />' />
                                                    <ext:Column ID="Column2" runat="server" Text="Nombre" Flex="35" DataIndex="Name" />
                                                </Columns>
                                            </ColumnModel>
                                            <View>
                                                <ext:GridView ID="GridView2" runat="server" EmptyText="No Images to Display" />
                                            </View>
                                            <SelectionModel>
                                                <ext:RowSelectionModel ID="RowSelectionModel2" runat="server" Mode="Single" />
                                            </SelectionModel>
                                            <Buttons>
                                                <ext:Button ID="btnDeleteImagecategory" runat="server" Text="Eliminar">
                                                    <DirectEvents>
                                                        <Click OnEvent="btnDeleteImageCategory_Click">
                                                            <EventMask ShowMask="true" Target="CustomTarget" CustomTarget="={#{categoryDetailsWindow}.body}" />
                                                            <ExtraParams>
                                                                <ext:Parameter Name="id" Value="#{Idcategory}.getValue()" Mode="Raw" />
                                                            </ExtraParams>
                                                        </Click>
                                                    </DirectEvents>
                                                </ext:Button>
                                            </Buttons>
                                        </ext:GridPanel>
                                    </Items>
                                </ext:FieldContainer>
                            </Items>
                        </ext:FieldSet>
                    </Items>
                </ext:FormPanel>
            </Items>
        </ext:TabPanel>
    </Items>
    <Buttons>
        <ext:Button ID="SaveButton" runat="server" Text="Save" Icon="Disk">
            <DirectEvents>
                <Click OnEvent="SaveCategory" Failure="Ext.MessageBox.alert('Saving failed', 'Error during ajax event');">
                    <EventMask ShowMask="true" Target="CustomTarget" CustomTarget="={#{categoryDetailsWindow}.body}" />
                    <ExtraParams>
                        <ext:Parameter Name="id" Value="#{Idcategory}.getValue()" Mode="Raw" />
                    </ExtraParams>
                </Click>
            </DirectEvents>
        </ext:Button>
        <ext:Button ID="CancelButton" runat="server" Text="Cancel" Icon="Cancel">
            <Listeners>
                <Click Handler="this.up('window').hide();" />
            </Listeners>
        </ext:Button>
    </Buttons>
</ext:Window>
